import { NavBar, DatePicker } from "antd-mobile";
import { useState, useMemo, useEffect } from "react";
import classnames from "classnames"
import "./index.scss"
import dayjs from "dayjs";
import _ from "lodash";
import { useSelector } from "react-redux";
import DailyBill from "./DailyBill";

const Month = () => {
  // 引入后台消费数据
  const billList = useSelector((state) => state.bill.billList)
  // console.log("消费数据(原始):",billList)
  // 按月分组:消费数据分组处理
  const monthGroup = useMemo(() => {
    // return出去计算之后的值
    return _.groupBy(billList, (item) => dayjs(item.date).format("YYYY | MM"))
  }, [billList])
  // console.log("消费数据(分组后):",monthGroup);

  /******状态变量******/
  // 显示隐藏状态
  const [isVisible, setIsVisible] = useState(false)
  // 当前年月
  const [currentDate, setCurrentDate] = useState(() => {
    return dayjs().format("YYYY | MM")//默认显示当前年月(2025 | 10)
  })
  // 当前选择月份对应的消费数据列表
  const [currentMonthList, setCurrentMonthList] = useState([])
  // 计算当前年月对应的消费数据列表(获取状态变量currentMonthList之后)
  // 支出/收入/结余的计算逻辑
  const monthResult = useMemo(() => {
    //支出
    const pay = currentMonthList.filter(item => item.type === 'pay').reduce((pre, cur) => {
      return pre + Number(cur.money)
    }, 0);
    //收入
    const income = currentMonthList.filter(item => item.type === 'income').reduce((pre, cur) => {
      return pre + Number(cur.money)
    }, 0);
    //结余
    const balance = income + pay;

    return { pay, income, balance }
  }, [currentMonthList])

  // 页面渲染时就有初始化数据
  useEffect(() => {
    // 当前时间
    const nowDate = dayjs().format("YYYY | MM");
    // 获取当前年月对应的消费数据
    if (monthGroup[nowDate]) {
      // 并存到状态变量currentMonthList中
      setCurrentMonthList(monthGroup[nowDate])
    }
  }, [monthGroup])

  // 按日分组
  const dayGroup = useMemo(() => {
    const groupData = _.groupBy(currentMonthList, item => dayjs(item.date).format("YYYY-MM-DD"));
    const keys = Object.keys(groupData);//获取所有日期,放进一个数组中
    return {
      groupData,
      keys
    }
  }, [currentMonthList])
  //console.log("按日分组:",dayGroup);

  /******事件******/
  const onConfirm = (value) => {
    setIsVisible(false)
    const date = dayjs(value).format("YYYY | MM");
    // 拿到当前年月对应的消费数据
    setCurrentMonthList(monthGroup[date])
    setCurrentDate(date)
    // console.log("用户选择的月份(日期格式优化后):",date);//2025 | 5
    // console.log("用户选择的月份(消费数据):",monthGroup[date]);//2025 | 5对应的消费数据
  }


  return (
    <div className="monthlyBill">
      <NavBar className="nav" backIcon={false}>月度收支</NavBar>
      <div className="content">
        <div className="header">
          {/* 时间切换区域 */}
          <div className="date" onClick={() => setIsVisible(true)}>
            <span className="text">{currentDate + ''}月账单</span>
            <span className={classnames("arrow", isVisible && "expand")}></span>
          </div>
          {/* 统计区域 */}
          <div className="twoLineOverview">
            <div className="item">
              <span className="money">{monthResult.pay.toFixed(2)}</span>
              <span className="type">支出</span>
            </div>
            <div className="item">
              <span className="money">{monthResult.income.toFixed(2)}</span>
              <span className="type">收入</span>
            </div>
            <div className="item">
              <span className="money">{monthResult.balance.toFixed(2)}</span>
              <span className="type">结余</span>
            </div>
          </div>
          {/* 月份选择器 */}
          <DatePicker
            className="kaDate"
            title="记账日期"
            precision="month"
            visible={isVisible}
            onClose={() => {
              setIsVisible(false)
            }}
            onConfirm={onConfirm}
            max={new Date()}
            defaultValue={new Date()}
          />
        </div>
        {/* 列表区域 */}
        {/* 传值:date是年月格式的字符串，billList是消费数据列表数组 */}
        {/* 遍历 */}
        {dayGroup.keys.map((key) => {
          return <DailyBill key={key} date={key} billList={dayGroup.groupData[key]} />
        })}
      </div>
    </div>
  )
}

export default Month;